<template>
  <page-header-wrapper :title="false">
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :xxl="6" :lg="8" :sm="8">
              <a-form-item label="任务名称">
                <a-input placeholder="请输入任务名称" v-model="queryParam.f_name" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="searchHa_task" icon="search">查询</a-button>
                <a-button icon="reload" style="margin-left: 8px" @click="reQuery">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div style="margin-bottom: 16px">
        <a-button type="primary" style="margin-left: 8px" @click="handleAdd" icon="plus">添加调度任务</a-button>
        <a-button type="primary" style="margin-left: 8px" @click="exportExcel" icon="export">导出调度任务</a-button>
        <a-dropdown>
          <a-menu slot="overlay">
            <a-menu-item>
              <a-popconfirm
                :title="'已选择' + selectedRowKeys.length + '项,确定删除吗？'"
                ok-text="确定"
                cancel-text="取消"
                @confirm="delHa_tasks"
              >
                <a-icon type="delete" />&nbsp;删除
              </a-popconfirm>
            </a-menu-item>
          </a-menu>
          <a-button v-show="selectedRowKeys.length > 0" style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>
      <div class="spin-content">
        已选择&nbsp;
        <a style="font-weight: 600" v-text="selectedRowKeys.length"></a>
        项&nbsp;
        <a style="margin-left: 24px" @click="() => (selectedRowKeys = [])">清空</a>
      </div>
      <a-table
        :scroll="{ x: 1500, y: 300 }"
        :columns="ucolumns"
        :data-source="udata"
        :pagination="upagination"
        :loading="loading"
        rowKey="id"
        @change="tableChange"
        size="middle"
        :bordered="ubordered"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: getCheckboxProps }"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
        </span>
        <span slot="operation" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record, true)">详情</a>
            <a-divider type="vertical" />
          </template>
          <template>
            <a @click="handleLog(record)">日志</a>
            <a-divider type="vertical" />
          </template>
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down" /> </a>
            <a-menu slot="overlay">
              <template v-if="record.enable === 0">
                <a-menu-item>
                  <a @click="handleEdit(record, false)">编辑</a>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm
                    title="确定启动吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="start(record.id)"
                  >
                    <a-icon slot="icon" type="check-circle" />
                    <a href="javascript:;">启动</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm
                    title="确定删除吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="delHa_taskById(record)"
                  >
                    <a-icon slot="icon" type="delete" />
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </template>
              <template v-if="record.enable === 1">
                <a-menu-item>
                  <a-popconfirm
                    title="确定暂停吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="pause(record.id)"
                  >
                    <a-icon slot="icon" type="stop" />
                    <a href="javascript:;">暂停</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm
                    title="确定执行吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="run(record.id, record.classname)"
                  >
                    <a-icon slot="icon" type="thunderbolt" />
                    <a href="javascript:;">执行</a>
                  </a-popconfirm>
                </a-menu-item>
              </template>
              
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </a-card>
    <a-drawer
      :title="isView ? '调度任务详情' : '调度任务编辑'"
      :width="720"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
      destroyOnClose
    >
      <edit ref="view" @close="onClose" @reloadList="searchHa_task"></edit>
    </a-drawer>
  </page-header-wrapper>
</template>

<style lang="less" src="@/style/base.less">
</style>

<script>
import { delHa_tasks, delHa_task, viewHa_task, saveHa_task, queryHa_taskList, output, enableTask, disableTask, executeTask } from '@/api/base/ha_task'
import edit from '@/views/base/Ha_taskEdit'
// 没有用到枚举作为查询条件的请删除
import { queryEnumerationValuesByName } from '@/api/base/enumeration'

export default {
  data() {
    return {
      advanced: false, // 查询条件是否展开
      loading: false, // 遮罩是否显示
      visible: false, // 抽屉是否可见
      ubordered: false, // 表格边框是否显示
      isView: false, // 是否查看
      queryParam: {}, // 查询条件
      selectedRowKeys: [], // 选中的行id
      udata: [], // 表格数据
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['20', '50', '100'],
      },
      ucolumns: [
        {
          title: '任务名',
          dataIndex: 'name',
          width: '1',
          sorter: (a, b) => String(a.name).localeCompare(String(b.name)),
          align: 'left',
        },
        {
          title: '任务类',
          dataIndex: 'classname',
          width: '1',
          sorter: (a, b) => String(a.classname).localeCompare(String(b.classname)),
          align: 'center',
        },
        {
          title: '表达式',
          dataIndex: 'cron',
          width: '1',
          sorter: (a, b) => String(a.cron).localeCompare(String(b.cron)),
          align: 'center',
        },
        {
          title: '最近执行IP',
          dataIndex: 'executeip',
          width: '1',
          sorter: (a, b) => String(a.executeip).localeCompare(String(b.executeip)),
          align: 'center',
        },
        {
          title: '最近执行时间',
          dataIndex: 'executetime',
          width: '1',
          sorter: (a, b) => String(a.executetime).localeCompare(String(b.executetime)),
          align: 'center',
        },
        {
          title: '是否启用',
          dataIndex: 'enable_text',
          width: '1',
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ], // 表头
    }
  },
  created() {
    // 没有用到枚举作为查询条件的请删除
    this.findEnumByName()
    this.findHa_taskList(this.queryParam)
  },
  methods: {
    /**
     *  查询枚举值,没有用到枚举作为查询条件的请删除
     */
    findEnumByName() {
      const parameter = []
      parameter.forEach((item) => {
        queryEnumerationValuesByName({ enName: item.enumName }).then((res) => {
          this[`${item.enname}List`] = res.data
          this[`${item.enname}List`].unshift({ id: '', description: '全部' })
          console.log(this[`${item.enname}List`])
        })
      })
    },
    /**
     *  查询调度任务列表
     */
    findHa_taskList(queryParam) {
      const a = Date.now()
      console.log('queryParam', queryParam)
      queryHa_taskList(queryParam).then((res) => {
        this.loading = true
        console.log('queryHa_taskList:', res.data)
        this.udata = res.data.records
        // 将当前页码和数量与后台绑定
        this.upagination.total = res.data.total
        this.upagination.current = res.data.current
        this.upagination.pageSize = res.data.size
        // 如果查询时间太短就给一个0.5秒的加载效果
        const b = Date.now()
        if (b - a < 500) {
          setTimeout(() => {
            this.loading = false
          }, 500)
        } else {
          this.loading = false
        }
      })
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery() {
      this.queryParam = {}
      this.findHa_taskList(this.queryParam)
    },
    /**
     * 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
     */
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('tableChange', pagination)
      console.log('filters', filters)
      console.log('sorter', sorter)
      console.log('{ currentDataSource }', { currentDataSource })
      this.queryParam.pageNumber = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      if (sorter != null && sorter.order != null) {
        this.queryParam.sort = sorter.field
        this.queryParam.order = sorter.order
      }
      this.findHa_taskList(this.queryParam)
    },
    /**
     * 查询
     */
    searchHa_task() {
      // 查询时将当前页码重置为1，否则会出现有数据但不显示的问题
      this.queryParam.pageNumber = 1
      // this.upagination.current = 1
      this.findHa_taskList(this.queryParam)
    },
    /**
     * 选中行数据时触发
     */
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * 打开抽屉
     */
    showDrawer() {
      this.visible = true
    },
    /**
     * 收回抽屉
     */
    onClose() {
      this.visible = false
    },
    /**
     * 进入新增页面
     */
    handleAdd() {
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.resetHa_task()
      }, 10)
    },
    /**
     * 进入编辑页面
     */
    handleEdit(res, isView) {
      this.isView = isView
      console.log('view', res.id)
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.findHa_taskById(res.id, isView)
      }, 10)
    },
    handleLog (record) {
      this.$router.push({ name: 'ha_task_logList', params: { taskid: record.id } });
    },
    /**
     * 删除调度任务
     */
    delHa_taskById(res) {
      delHa_task(res.id).then((res) => {
        console.log('delHa_task:', res)
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.searchHa_task()
          this.$message.success('删除成功')
        }
      })
    },
    /**
     * 批量删除调度任务
     */
    delHa_tasks() {
      delHa_tasks(this.selectedRowKeys.toString()).then((res) => {
        console.log('delHa_tasks:', res)
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.searchHa_task()
          this.$message.success('删除成功')
        }
      })
    },
    /**
     *  导出Excel
     */
    exportExcel() {
      output(this.queryParam)
        .then((response) => {
          var blob = new Blob([response])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '调度任务.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch(function () {
          console.log(error)
        })
    },
    start (id) {
      enableTask({ id: id}).then(res =>{
        if (res.code === 0) {
          this.searchHa_task()
        }
      })
    },
    pause (id) {
      disableTask({ id: id }).then(res => {
        if (res.code === 0) {
          this.searchHa_task()
        }
      })
    },
    run (id, classname) {
      executeTask({ id: id }).then(res =>{});
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.enable === 1,
        },
      }
    }
  },
  components: {
    edit,
  },
}
</script>